<template>
  <el-dialog :title="operateOption" :visible.sync="visible" @close="handleCancel">
    <el-form label-width="100px">
      <el-form-item label="操作角色">
        <span>{{ selectedRoleNames }}</span>
      </el-form-item>

      <el-tree
        ref="tree"
        :data="roleResourceData"
        show-checkbox
        node-key="id"
        :props="{ children: 'children', label: 'name'}"
        :default-checked-keys="selectedKeys"
      />
      <div style="margin-top: 10%;">
        <el-table ref="roleCompanyTable" :data="roleCompanyData" @select="handleSelectionChange" @select-all="handleSelectAll">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="公司名称" />
          <el-table-column prop="code" label="公司编号" />
        </el-table>
      </div>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel()">取 消</el-button>
      <el-button v-if="operateOption== '资源分配' " type="primary" @click="handleConfirm()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { allocateRoleResourceAndCompanyAPI } from '@/api/role'
import { Message } from 'element-ui'
export default {
  name: 'AllocateResourceForm',
  props: {
    // 可见性
    visible: {
      type: Boolean,
      required: true
    },
    // 角色资源数据
    roleResourceData: {
      type: Array,
      required: true,
      default: () => []
    },
    // 表单上方显示的操作角色名称
    selectedRoleNames: {
      type: String,
      required: true
    },
    // 当前表单操作的角色ids
    selectedRoleIds: {
      type: Array,
      required: true
    },
    // 角色公司数据
    roleCompanyData: {
      type: Array,
      required: true,
      default: () => []
    },
    // 操作名称：资源分配 ，查看权限
    operateOption: {
      type: String,
      required: true

    }

  },
  data() {
    return {

      selectedCompanyIds: [],
      selectedResourceIds: [],
      selectedRows: []

    }
  },

  // computed计算属性，当数据发生变化时，自动重新计算
  computed: {
    // 用于显示表单打开时，当前角色已经分配资源的数据
    selectedKeys() {
      // 递归获取所有 existsFlag 为 1 的节点 id
      const getSelectedKeys = (nodes) => {
        let keys = []
        nodes.forEach(node => {
          if (node.existsFlag === 1) {
            keys.push(node.id)
          }
          if (node.children && node.children.length) {
            keys = keys.concat(getSelectedKeys(node.children))
          }
        })
        return keys
      }
      return getSelectedKeys(this.roleResourceData)
    }
  },
  watch: {
    // 观测角色的公司信息是否改变，如果改变，则更改勾选状态
    roleCompanyData: {
      handler(newVal) {
        this.$nextTick(() => {
          newVal.forEach(row => {
            if (row.bindStatus === '1') {
              this.$refs.roleCompanyTable.toggleRowSelection(row, true)
            }
          })
        })
      }
    }
  },
  methods: {

    getSelectedResourceIds() {
      // 使用 this.$refs.tree.getCheckedKeys() 来获取选中的节点ID
      this.selectedResourceIds = this.$refs.tree.getCheckedKeys()
    },

    // 提交表单
    async handleConfirm() {
      this.getSelectedResourceIds()// 将selectedResourceIds 选中的资源id列表更新

      this.selectedCompanyIds = this.selectedRows.map(row => row.id) // 将selectedCompanyIds 选中的公司id列表更新

      const request = {
        roleIds: this.selectedRoleIds,
        authCompanyIds: this.selectedCompanyIds,
        resourceIds: this.selectedResourceIds,
        companyId: this.$store.getters.companyId,
        orgId: this.$store.getters.orgId,
        tenantId: this.$store.getters.tenantId

      }
      const response = await allocateRoleResourceAndCompanyAPI(request)
      if (response === true) {
        Message.success('操作成功')
      } else {
        Message.error('操作失败，请稍后再试')
      }

      this.$emit('update:visible', false)
    },
    handleCancel() {
      this.$emit('update:visible', false)
      this.getSelectedResourceIds()
      console.log(this.selectedResourceIds)
    },

    // 公司列表多选框
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    handleSelectAll(selection) {
      this.selectedRows = selection
    }
  }
}
</script>
